package indi.zn.commons.event;

import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;

import indi.zn.commons.collection.MapType;
import indi.zn.commons.collection.Maps;
import indi.zn.commons.threads.fork.ExecutorType;

public class EventBusFactory {

	private Map<String, EventBus> busMap;

	public EventBusFactory() {
		busMap = Maps.newMap(MapType.ConcurrentMap);	
		}

	public EventBus getEventBus(String name, boolean asyn, ExecutorType type, int n) {

		if (asyn) {
			return getAsynEventBus(name, type, n);
		} else {
			return getEventBus(name);
		}

	}

	public EventBus getEventBus(String name) {

		EventBus eb = busMap.get(name);

		if (eb == null) {

			eb = new EventBus(name);
			busMap.put(name, eb);
		}

		return eb;
	}

	public EventBus getAsynEventBus(String name, ExecutorType type, Integer n) {

		Executor executor = null;

		EventBus eb = busMap.get(name);

		if (eb == null) {

		

			if (ExecutorType.AUTO == type) {
				executor = Executors.newCachedThreadPool();
			}
			if (ExecutorType.SINGLE == type) {
				executor = Executors.newSingleThreadExecutor();
			}
			if (ExecutorType.FIXED == type) {
				executor = Executors.newFixedThreadPool(n);
			}
			
			eb = new AsyncEventBus(name, executor);
			busMap.put(name, eb);

		}

		return eb;

	}

}
